package com.lemon.service;

import java.util.Date;
import java.util.List;

import com.lemon.dao.MenuDao;
import com.lemon.domain.Menu;

public class MenuService {

	private MenuDao dao = new MenuDao();

	public Menu get(Long id) {
		return dao.get(id);
	}
	
	public List<Menu> listSubmenu(Long id) {
		return dao.listSubmenu(id);
	}
	
	public String generateNavigation() {
		StringBuilder builder = new StringBuilder();
		builder.append("<ul id=\"nav-mobile\" class=\"side-nav fixed\" style=\"transform: translateX(0%);\">")
			.append("<li class=\"no-padding\">")
			.append(generateNavigation(listSubmenu(null)))
			.append("</li>")
			.append("</ul>");
		
		return builder.toString();
	}
	
	/**
	 * 利用递归方法
	 * 生成左侧导航栏的html字符
	 * @param menus
	 * @return
	 */
	public String generateNavigation(List<Menu> menus) {
		if (menus == null) {
			return null;
		}
		
		StringBuilder builder = new StringBuilder("<ul class=\"collapsible collapsible-accordion\">");
		for (Menu m : menus) {
			builder.append("<li class=\"bold\">")
				.append("<a class=\"collapsible-header  waves-effect waves-teal\" href=\"")
				.append(m.getUrl())
				.append("\">")
				.append(m.getName())
				.append("</a>")
				.append("<div class=\"collapsible-body\">")
				.append(generateNavigation(m.getSubmenuList()))
				.append("</div>")
				.append("</li>");
		}
		builder.append("</ul>");
		
		return builder.toString();
	}
	
	public String listToHtml() {
		return listToHtml(listSubmenu(null));
	}
	
	/**
	 * 生成以层级方式展示菜单列表的html字符
	 * @param menus
	 * @return
	 */
	public String listToHtml(List<Menu> menus) {
		if (menus == null) {
			return null;
		}
		
		StringBuilder builder = new StringBuilder("<ul class=\"collapsible\" data-collapsible=\"expandable\" style=\"margin: 0px; border: none;\">");
		for (Menu d : menus) {
			builder.append("<li>")
				.append("<div class=\"collapsible-header\" menu-id=\"")
				.append(d.getId())
				.append("\">")
				.append(d.getName())
				.append("</div>")
				.append("<div class=\"collapsible-body\">")
				.append(listToHtml(d.getSubmenuList()))
				.append("</div>")
				.append("</li>");
		}
		builder.append("</ul>");
		
		return builder.toString();
	}
	
	public List<Menu> list() {
		return dao.list();
	}
	
	public Long save(Menu m) {
		m.setCreateTime(new Date());
		return dao.save(m);
	}
	
	public int delete(Long id) {
		return dao.delete(id);
	}
	
	public int update(Menu m) {
		m.setUpdateTime(new Date());
		return dao.update(m);
	}
}
